package com.ygqh.baby.handler;

import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.UserCountWrapper;
import com.ygqh.baby.model.UserCountWrapper.UserCountModel;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author: sunshuo
 * @Date: 2019/9/5/005 18:16
 * @Version: 1.0
 */
@Component
public class OrderCountHandler {

    @Autowired
    private YgOrderService ygOrderService;

    /**
     * 购买用户数环比
     *
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param platformNo 销售平台编号
     * @param type 区间type
     */
    public List<UserCountModel> userCountRingRatio(Date startDate, Date endDate, String platformNo, int type) {
        List<YgOrder> orderList = ygOrderService.findByPaidTime(startDate, endDate, platformNo);
        if (CollectionUtils.isEmpty(orderList)) {
            return Collections.emptyList();
        }
        UserCountWrapper wrapper = createUserCountWrapper(startDate, endDate, type);
        if (wrapper == null) {
            return Collections.emptyList();
        }
        orderList.forEach(order -> wrapper.addUser(order.getPaidTime(), order.getUserId(), order.getNewPaidUser()));
        return wrapper.getUserCountModel();
    }

    private UserCountWrapper createUserCountWrapper(Date startDate, Date endDate, int type) {
        if (!endDate.after(startDate)) {
            return null;
        }
        Date tempEndDate = getIntervalEndDate(startDate, type);
        if (tempEndDate.after(endDate)) {
            tempEndDate = endDate;
        }
        UserCountWrapper wrapper = new UserCountWrapper(startDate, tempEndDate);
        wrapper.setNext(createUserCountWrapper(tempEndDate, endDate, type));
        return wrapper;
    }

    private Date getIntervalEndDate(Date startDate, int type) {
        switch (type) {
            case Calendar.DATE:
                return DateConvertUtils.addDay(startDate, 1);
            case Calendar.WEEK_OF_YEAR:
                return DateConvertUtils.addWeek(startDate, 1);
            case Calendar.MONTH:
                return DateConvertUtils.addMonth(startDate, 1);
            case Calendar.YEAR:
                return DateConvertUtils.addYear(startDate, 1);
            default:
                throw new YgException("未知时间周期类型");
        }
    }
}
